<?php
// application/modules/default/controllers/UserController.php
/**
 * demo-zf application
 *
 * default\UserController
 *
 * @uses Lib_Default_ActionAbstract
 * @author Adam Pilacki <adam.pilacki@gmail.com>
 */
class UserController
    extends Lib_Default_ActionAbstract
{
    /**
     * @var Zend_Translate
     */
    private $_translator = null;

    public function init()
    {
        parent::init();

        $this->_translator = $this->_bootstrap->getResource('Translate');
    }

    /**
     * See {@link Lib_ActionAbstract::_resolveLocation}
     */
    protected final function _resolveLocation()
    {
        $actionName = $this->getRequest()->getActionName();

        /* redirect if already authenticated */
        if ($this->_isAuthenticated && in_array($actionName, array('login', 'register', 'create'))) {
            $this->_redirect($this->_sessionNamespace->lastPage);
        }

        /* if not post */
        if (!$this->_request->isPost() && in_array($actionName, array('login', 'create'))) {
            $this->_redirect($this->_config->urls->redirectNotAuthenticated);
        }

    }

    /**
     * Action - display register form (add)
     */
    public final function registerAction()
    {
        $this->view->registerForm = new Form_UserRegister();
        $this->view->noLoginForm = true;
    }

    /**
     * Action - process form and create new user if form is valid
     */
    public final function createAction()
    {
        $post = $this->getRequest()->getPost('UserRegister', array());

        $form = new Form_UserRegister();

        /* indicate if password and confirmation are both set */
        $passwordsSet = !empty($post['password']) && !empty($post['passwordConfirm']);

        /**
         * TODO implement passwords compare validation in more civilized way - current solution is very ugly :D
         */
        if (!$form->isValid($post) ||
            !$passwordsSet ||
            $post['password'] != $post['passwordConfirm']) {

            /* add validation message if password and confirmation do not match  */
            if ($passwordsSet && $post['login'] !== $post['passwordConfirm']) {
                $form->getElement('password')->addError($this->_translator->translate('Hasło i potwierdzenie muszą być identyczne'));
            }

            $form->populate($post);
            $this->view->registerForm = $form;
            $this->view->noLoginForm = true;
            $this->view->message = $this->_translator->translate('Formularz zawiera błędy');
            $this->render('register');
            return;
        }

        $user = AdamP_Model::getTable('Users')->findOneByLogin($post['login']);

        if (!empty($user)) {
            $form->populate($post);
            $this->view->registerForm = $form;
            $this->view->noLoginForm = true;
            $this->view->message = $this->_translator->translate('Użytkownik o podanym loginie już istnieje - wybierz inny');
            $this->render('register');
            return;
        }

        /* save new user to db */
        $user = AdamP_Model::getTable('Users')->createRow();
        $user->login = $post['login'];
        $user->password = $post['password'];
        $user->save();

        /* authenticate user and redirect */
        $this->_processAuthentication($post['login'], $post['password']);
    }

    /**
     * Action - logs user in and redirects to proper url
     */
    public final function loginAction()
    {
        $post = $this->_request->getPost('UserLogin', array());

        if (!isset($post['login']) || !isset($post['password'])) {
            $this->_redirect($this->_config->urls->redirectNotAuthenticated);
        }

        /* authenticate user and redirect */
        $this->_processAuthentication($post['login'], $post['password']);
    }

    /**
     * Action - logs user out and redirects to proper url
     */
    public final function logoutAction()
    {
        /* redirect not authenticated */
        if (!$this->_isAuthenticated) {
            $this->_redirect($this->_sessionNamespace->lastPage);
        }

        /* clear current auth indentity */
        Zend_Auth::getInstance()->clearIdentity();

        /* reset auth user settings */
        $this->_sessionNamespace->authUserData = array();

        /* clear auth cookie */
        setcookie('authenticated', null, null, '/');

        $this->_redirect($this->_config->urls->redirectNotAuthenticated);
    }

    /**
     * Authenticate user and redirect
     *
     * @param string $login
     * @param string $password
     */
    private function _processAuthentication($login, $password)
    {
        $result = Zend_Auth::getInstance()->authenticate(new Lib_AuthAdapter($login, $password));

        /* @var $messenger Zend_Controller_Action_Helper_FlashMessenger */
        if ($result->isValid()) {
            $this->_helper->flashMessenger
                ->setNamespace('success')
                ->addMessage($this->_translator->translate('Logowanie wykonane pomyślnie'));
            $this->_redirect($this->_sessionNamespace->lastPage);
        }

        $this->_helper->flashMessenger
            ->setNamespace('error')
            ->addMessage($this->_translator->translate('Logowanie zakończone niepowodzeniem'));
        $this->_redirect($this->_config->urls->redirectNotAuthenticated);
    }

      /**
       * TODO implement code below or remove it if not necessary
       */
//    private function _authenticate($login, $password)
//    {
//        $result = Zend_Auth::getInstance()->authenticate(new Lib_AuthAdapter($login, $password));
//        switch ($result->getCode()) {
//            case Zend_Auth_Result::FAILURE:
//                /* handle this situation */
//                break;
//
//           case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
//                /* do stuff for invalid credential */
//                break;
//
//            case Zend_Auth_Result::SUCCESS:
//                /* do stuff for successful authentication */
//                break;
//
//            default:
//                /* do stuff for other failure */
//                break;
//           }
//        return $result->isValid();
//    }
}